

# -*- coding: UTF-8 -*-
import asyncio
from concurrent.futures import ThreadPoolExecutor
import contextvars
import functools
import inspect

from lj_tool import tool_sys


def lj_async(func):
    """异步运行 - 无返回值

    Args:
        func (Function): 函数
    """
    def wrapper(*args, **kwargs):
        async def async_fun():
            func(*args, **kwargs)
        async_fun(async_fun())
    return wrapper


def async_start_run(func):
    try:
        if inspect.iscoroutine(func):
            asyncio.run(func)
        elif callable(func):
            asyncio.run(func())
    except:
        print("LJ - 事件循环停止...")
        # loop = asyncio.get_event_loop()
        # loop.close()


async def async_thread_run(func, /, *args, **kwargs):
    # loop = asyncio.get_running_loop()
    # ctx = contextvars.copy_context()
    # func_call = functools.partial(ctx.run, func, *args, **kwargs)
    # return await loop.run_in_executor(None, func_call)

    return await asyncio.to_thread(func)

newexecutor = ThreadPoolExecutor()


async def async_thread_run_2(func):  # 测试新建线程
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(newexecutor, func)  # 执行阻塞函数


def close():
    loop = asyncio.get_event_loop()
    loop.stop()
    print("LJ - 退出 async 事件循环...")


tool_sys.exit_listen(close)
